package com.hoperun.preparedisplay.util;

import java.io.IOException;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

public class WebServiceUtils {
	
	public static String MACHINE_NO = "MACHINENO";
	public static String MACHINE_STATE = "STATE";
	public static String MACHINE_PLANTYPE = "PLANTYPE";
	public static String OPT_FLAG = "OPT_FLAG";
	public static String MSG_INFO = "MSG_INFO";
	
	private static String url = "http://10.20.133.53:8080/szerp/PublicWebServiceInterface";
	private static String nameSpace = "http://service.commons.hoperun.com/";
	private static String methodName = "getMachineInfoList";
	private static int timeout = 5000;
	
//	static {
//		url = Setting.getUrl();
//		timeout = Setting.getSocketTimeout();
//	}

	public static synchronized String getMachineInfoList(String ProMachine) {
		
		url = Setting.getUrl();
		timeout = Setting.getSocketTimeout();
		
		SoapObject request = new SoapObject(nameSpace, methodName);
		if(ProMachine != null) {
			request.addProperty("arg0", ProMachine);
		}
		final SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
		envelope.dotNet = false;
		envelope.setOutputSoapObject(request);
		
		final HttpTransportSE ht = new HttpTransportSE(url, timeout);
		ht.debug = true;
		FutureTask<String> future = new FutureTask<String>(
				new Callable<String>() {

					@Override
					public String call() {
						String result = "";
						try {
							ht.call(nameSpace + methodName, envelope);
							if(envelope.getResponse() != null) {
								result = envelope.getResponse().toString();
							}
						} catch (IOException e) {
							result = "[{\"OPT_FLAG\":1,\"MSG_INFO\":\""+ e.toString()+"\"}]";
						} catch (XmlPullParserException e) {
							result = "[{\"OPT_FLAG\":1,\"MSG_INFO\":\""+ e.toString()+"\"}]";
						}
						
						return result;
					}
				}
		);
		
		new Thread(future).start();
		try {
			return future.get();
		} catch (InterruptedException e) {
			return "[{\"OPT_FLAG\":1,\"MSG_INFO\":\""+ e.toString()+"\"}]";
		} catch (ExecutionException e) {
			return "[{\"OPT_FLAG\":1,\"MSG_INFO\":\""+ e.toString()+"\"}]";
		}
	}
}
